package com.example.widget_lib.widget.ring;


import com.example.widget_lib.ResourceTable;
import com.example.widget_lib.bean.CircleBean;
import com.example.widget_lib.utils.AttrUtils;
import com.example.widget_lib.utils.LogUtil;
import com.example.widget_lib.utils.PxUtil;
import com.example.widget_lib.widget.PointView;
import com.example.widget_lib.widget.base.CircleCenterStyle;
import com.example.widget_lib.widget.progress.circle.CircleView;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextAlignment;
import ohos.app.Context;
import ohos.global.resource.solidxml.TypedAttribute;

import java.util.HashMap;
import java.util.List;

/**
 * 自定义分段圆环（内含图例）
 *
 * @author hongbing
 * @since 20181219
 * 自定义属性：https://blog.csdn.net/android_cai_niao/article/details/43701747
 */
public class LegendRingView extends StackLayout {

    private static final String TAG = LegendRingView.class.getSimpleName();
    private int ordinal;

    private CircleView mCircleView;
    private DirectionalLayout mLrvLayout;

    // 图形中间样式
    private CircleCenterStyle mCircleStyle;
    // 圆环高度
    private int mCircleHeight;
    // 环的厚度
    private int mBorderW;
    // 圆环上下内边距
    private int mCirclePaddingTop, mCirclePaddingBottom;
    private String mCenterStr;
    private int mCenterTxtSize;
    private int mCenterTxtColor;
    // 图例的列宽
    private int mColumnWidth;
    // 图例行间距
    private int mLegendVerMargin;
    // 图例字体颜色
    private int mlabelColor;
    // 图例字体大小
    private int mLabelSize;
    // 图例文案和圆点的间距
    private int mLegendLabelAndPointMargin;
    // 图例每行第一个左侧偏移量
    private int mLegendOffsetLeft;
    // 动态计算出来的列数
    private int mColumn;
    // 圆环颜色集合
    private int[] circle_colors;
    private int width;
    private int pointWH = 50;


    public LegendRingView(Context context) {
        this(context, null);
    }

    public LegendRingView(Context context, AttrSet attrSet) {
        super(context, attrSet);
        init(context, attrSet);
    }

    public LegendRingView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        init(context, attrSet);
    }

    private void init(Context context, AttrSet attrs) {
//        setEstimateSizeListener(this::onEstimateSize);
        setBindStateChangedListener(new BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                /**
                 * 动态计算列数
                 */
                autoCaclColumn();
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {

            }
        });
        mCircleHeight = AttrUtils.getDimensionFromAttr(attrs, "legendRingView_lrv_circle_height", (int) PxUtil.vp2px(110));
        mBorderW = AttrUtils.getDimensionFromAttr(attrs, "legendRingView_lrv_circle_boderW", (int) PxUtil.vp2px(10));
        LogUtil.loge("======" + mBorderW + "=========");
        mCirclePaddingTop = AttrUtils.getDimensionFromAttr(attrs, "legendRingView_lrv_circle_paddingTop", (int) PxUtil.vp2px(15));
        mCirclePaddingBottom = AttrUtils.getDimensionFromAttr(attrs, "legendRingView_lrv_circle_paddingBottom", (int) PxUtil.vp2px(15));
        mCenterStr = AttrUtils.getStringFromAttr(attrs, "legendRingView_lrv_circle_center_txt", "测试");
        mCenterTxtSize = AttrUtils.getDimensionFromAttr(attrs, "legendRingView_lrv_circle_center_txt_size", (int) PxUtil.fp2px(12));
        mCenterTxtColor = AttrUtils.getColorFromAttr(attrs, "legendRingView_lrv_circle_center_txt_color", Color.getIntColor("#2A2A2A"));
        mlabelColor = AttrUtils.getColorFromAttr(attrs, "legendRingView_lrv_legend_font_color", Color.getIntColor("#2A2A2A"));
        mLabelSize = AttrUtils.getDimensionFromAttr(attrs, "legendRingView_lrv_legend_font_size", (int) PxUtil.fp2px(12));
        LogUtil.loge("======1=====");
        mColumnWidth = AttrUtils.getDimensionFromAttr(attrs, "legendRingView_lrv_legend_columnW", (int) PxUtil.vp2px(42));
        mLegendVerMargin = AttrUtils.getDimensionFromAttr(attrs, "legendRingView_lrv_legend_vertical_margin", (int) PxUtil.vp2px(8));
        mLegendLabelAndPointMargin = AttrUtils.getDimensionFromAttr(attrs, "legendRingView_lrv_legend_labelAndPoint_margin", (int) PxUtil.vp2px(4));
        mLegendOffsetLeft = AttrUtils.getDimensionFromAttr(attrs, "legendRingView_lrv_offset_left", 0);
        ordinal = AttrUtils.getIntegerFromAttr(attrs, "ordinal", 0);


        mContext = context;
        // 将自定义layout装载进来
//        LayoutInflater.from(context).inflate(R.layout.legend_circleview_layout, this, true);
        Component parse = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_legend_circleview_layout, this, true);
        mCircleView = ((CircleView) parse.findComponentById(ResourceTable.Id_circle_view));
        mCircleView.setHeight(mCircleHeight);
        mCircleView.setWidth(mCircleHeight);
        mCircleView.setCenterStyle(ordinal);
        LogUtil.loge("======" + mBorderW + "=========");
        mCircleView.setBorderW(mBorderW);


        // 设置圆环大小
//        DirectionalLayout.LayoutConfig params = new DirectionalLayout.LayoutConfig((int) PxUtil.vp2px(200), mCircleHeight);
//        LayoutConfig layoutConfig = new LayoutConfig((int) PxUtil.vp2px(200), mCircleHeight);
//        mCircleView.setLayoutConfig(params);
        // 设置圆环上下内边距
        mCircleView.setPadding(30, 30, 30, 30);
        circle_colors = mCircleView.getCircleColos();
        mCircleView.setCenterStr(mCenterStr);
        mCircleView.setCenterTxtSize(mCenterTxtSize);
        mCircleView.setCenterTxtColor(mCenterTxtColor);
        mLrvLayout = ((DirectionalLayout) parse.findComponentById(ResourceTable.Id_lrv_layout));
//        mLrvLayout.setAlignment(LayoutAlignment.HORIZONTAL_CENTER);
    }


    /**
     * 动态计算列数
     */
    private void autoCaclColumn() {
//        DirectionalLayout.LayoutConfig params = (DirectionalLayout.LayoutConfig) mLrvLayout.getLayoutConfig();
//        int margin = params.leftMargin + params.rightMargin;
//        // 计算每行显示列数
//        mColumn = (mLrvLayout.getMeasuredWidth() - margin) / mColumnWidth;
        width = getWidth();
        int padding = getPaddingLeft() + getPaddingRight();

        mColumn = (int) ((width - padding) / (mColumnWidth + pointWH));
//        mColumn = (int) ((width - margin) / (PxUtil.vp2px(42) + PxUtil.vp2px(50)));
//        LogUtil.loge("201812201056", "动态计算出的列数 = " + mColumn +
//                "->MeasuredWidth = " + mLrvLayout.getWidth() + "->margin = " + margin);
    }

    public int max() {
        return mCircleView.getMax();
    }

    public void setCircleColors(int... circle_colors) {
        this.circle_colors = circle_colors;
        mCircleView.setCircleColors(circle_colors);
    }

    public void setCircleColorsArr(int[] circle_colors) {
        this.circle_colors = circle_colors;
        mCircleView.setCircleColors(circle_colors);
    }

    public void setCenterStr(String centerStr) {
        mCenterStr = centerStr;
        if (mCircleView!=null){
            mCircleView.setCenterStr(mCenterStr);
        }
    }

    public void setCircleViewBorderW(int borderW) {
        mBorderW = (int) PxUtil.vp2px(borderW);
    }

    public CircleView getCircleView() {
        return mCircleView;
    }

    public void setEmpty() {
        setData(null, null);
    }

    public void setData(final List<CircleBean> list, final List<String> legends) {
        if (list == null && legends == null) {
            mLrvLayout.removeAllComponents();
            mCircleView.setEmpty();
            return;
        }

        if (list.isEmpty() && legends.isEmpty()) {
            mLrvLayout.removeAllComponents();
            mCircleView.setEmpty();
            return;
        }

        getContext().getUITaskDispatcher().delayDispatch(() -> {
            if (mColumn <= 0) { // view的大小未确定
                return;
            }
            if (list.size() != legends.size()) {
                throw new IllegalArgumentException("标签和环形集合大小不一致...");
            }

            LogUtil.loge("201812201056", "setData...");
            mCircleView.setData(list);

            int size = legends.size();

            // 图例行数
            int circulation = size / mColumn + (size % mColumn > 0 ? 1 : 0);
            LogUtil.loge("201812201056", "=====mColumn = " + mColumn + "图例行数 = " + circulation + "->集合总数size = " + size
                    + "->size / mColumn = " + (size / mColumn) + "->size % mColumn = " + (size % mColumn));
            if (mColumn > size) {
                mColumn = size;
            }

            // 先清空之前的子view
            mLrvLayout.removeAllComponents(); // 会导致onMeasure重新测量
            DirectionalLayout labelLayout;
            DirectionalLayout.LayoutConfig params = new DirectionalLayout.LayoutConfig(LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_CONTENT);
//            StackLayout.LayoutConfig sonParams = new LayoutConfig(LayoutConfig.MATCH_CONTENT, LayoutConfig.MATCH_CONTENT);
            LogUtil.loge("======" + circulation + "======");
            for (int i = 0; i < circulation; i++) {
                labelLayout = new DirectionalLayout(mContext);
                labelLayout.setOrientation(DirectionalLayout.HORIZONTAL);
                labelLayout.setLayoutConfig(params);
//                    linearLayout.setBackgroundColor(Color.rgb(123, 180, 248));
                if (circulation == 1) { // 只有一行，水平居中
                    labelLayout.setAlignment(LayoutAlignment.CENTER);
                } else { // 左对齐
//                    labelLayout.setHeight(circulation);
                    labelLayout.setAlignment(LayoutAlignment.LEFT | LayoutAlignment.VERTICAL_CENTER);
                    if (i > 0) { // 大于一行,第一行不设置行间上间距
                        params.setMarginTop(mLegendVerMargin);
                    }
                    params.setMarginLeft(mLegendOffsetLeft);
                }
                for (int j = 0; j < mColumn; j++) { // 创建label

                    if (i * mColumn + j > size - 1) { // 全取干净了
                        break;
                    }

                    PointView pointView = new PointView(mContext);
                    pointView.setPointWH(pointWH);
                    pointView.setColor(new Color(circle_colors[i * mColumn + j]));
                    pointView.setWidth(pointWH);
                    pointView.setHeight(pointWH);

//                    if (j > 0) {
//                        if (legends.get(i * mColumn + j - 1).length() > 2) { // 针对三个文字的间距设置
//                            sonParams.setMarginLeft((int) PxUtil.vp2px(12));
//                            pointView.setLayoutConfig(sonParams);
//                        }
//                    }
                    labelLayout.addComponent(pointView);
                    Text labelTv = new Text(mContext);
                    String text = legends.get(i * mColumn + j);
                    labelTv.setTextAlignment(TextAlignment.VERTICAL_CENTER);
                    labelTv.setPadding(mLegendLabelAndPointMargin, 0, 0, 0);
                    labelTv.setWidth(mColumnWidth);
                    labelTv.setTextSize(mLabelSize);//mLabelSize
                    labelTv.setTextColor(new Color(mlabelColor));
                    labelTv.setText(text);
                    labelLayout.addComponent(labelTv);

                }
                mLrvLayout.addComponent(labelLayout); // 会导致onMeasure重新测量
            }
//            invalidate();

        }, 50);
    }

    @Override
    public void addDrawTask(DrawTask task) {
        super.addDrawTask(task);
        task.onDraw(this, mCanvasForTaskOverContent);
    }

    public void setImagePic(int imagePicId) {
        if (mCircleView!=null){
            mCircleView.setImagePic(imagePicId);
        }
    }

}
